from goods.models import GoodsChannel,GoodsCategory


def get_categories():
    """获取三级商品表字典"""
    # 展示广告栏{'组1'：{'channel':[],'sub_cats':[xx]}}....
    categories = {}
    # 查到所有一级商品所有组（查询集）
    categories_group_qs = GoodsChannel.objects.order_by('group_id', 'sequence')
    # categories_group 所有频道（组）
    for categories_group in categories_group_qs:
        group_id = categories_group.group_id
        if group_id not in categories:
            categories[group_id] = {'channels': [], 'sub_cats': []}
        cat1 = categories_group.category
        # 添加一组的属性url
        cat1.url = categories_group.url
        categories[group_id]['channels'].append(cat1)
        # 一组中所有的二级模型（查询集）
        cat2_qs = cat1.subs.all()
        for cat2 in cat2_qs:
            # 一组中所有的三级
            cat3_qs = cat2.subs.all()
            # 定义cat2属性 cat2.sub_cats
            cat2.sub_cats = cat3_qs
            categories[group_id]['sub_cats'].append(cat2)
    return categories